import {BrowserWindow, dialog, ipcMain} from "electron";

const { exec } = require('child_process');

export async function handleFileOpen (e, opt) {
    const { canceled, filePaths } = await dialog.showOpenDialog(opt);
    if (!canceled) {
        return filePaths;
    }
}





export function setIpc(){
    ipcMain.handle('dialog:selectFile', handleFileOpen);

    //监听渲染进程发送的消息
    ipcMain.on('set-title', (event, title) => {
        //通过发送者获取窗口窗口
        const win = BrowserWindow.fromWebContents(event.sender);
        //修改窗口标题
        win.setTitle(title);
    });

    //打开图片
    ipcMain.on('open-file', (event, img) => {
        openFileWithDefaultApp(img);
    });

}



export function openFileWithDefaultApp(imagePath) {
    let command;
    if (process.platform === 'win32') {
        command = `start "" "${imagePath}"`;
    } else if (process.platform === 'darwin') {
        command = `open "${imagePath}"`;
    } else {
        command = `xdg-open "${imagePath}"`;
    }

    exec(command, (error, stdout, stderr) => {
        if (error) {
            console.error(`Error opening image: ${error.message}`);
            return;
        }
        if (stderr) {
            console.error(`Stderr: ${stderr}`);
            return;
        }
        console.log(`Image opened successfully: ${stdout}`);
    });
}